package site.wanjiahao.handler.server;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import site.wanjiahao.factory.UserServiceFactory;
import site.wanjiahao.message.request.LoginRequestMessage;
import site.wanjiahao.message.response.LoginResponseMessage;
import site.wanjiahao.session.SessionFactory;

@ChannelHandler.Sharable
public class LoginRequestMessageHandler extends SimpleChannelInboundHandler<LoginRequestMessage> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, LoginRequestMessage msg) throws Exception {
        // 查询用户是否存在
        boolean isLogin = UserServiceFactory.getUserService().login(msg.getUsername(), msg.getPassword());
        if (isLogin) {
            // 保存登录用户
            SessionFactory.getSession().bind(msg.getUsername(), ctx.channel());
        }
        LoginResponseMessage loginResponseMessage = new LoginResponseMessage(isLogin, isLogin ? "登录成功" : "账号或者密码错误");
        ctx.writeAndFlush(loginResponseMessage);
    }
}
